//
//  AppDelegate.m
//  AirportTraffic
//
//  Created by PJ Gray on 4/18/08.
//  Copyright 2008 SayGoodnight Software. All rights reserved.
//

#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>

#import "AppDelegate.h"


@implementation AppDelegate

-(void)dealloc
{
    [statusItem release];
      [super dealloc];
}

- (void) readDatFile
{
	FILE *infile;	
	char inputFilename[] = "airporttraffic.dat";
	
	infile = fopen(inputFilename, "r");

	if (infile != NULL) 
	{
		fscanf(infile, "%f\n%f\n%lu\n%lu\n", &totalInMegs, &totalOutMegs, &prevInVal, &prevOutVal);
		fclose(infile);
	}
}

- (void)windowDidBecomeKey: (NSNotification*) aNotification;
{
	if (timer)
	{
		[timer invalidate];
		[timer release];

		[timerWriteToDisk invalidate];
		[timerWriteToDisk release];
	
		timer = 0;
		timerWriteToDisk = 0;
	}
}

-(IBAction)resetTotalGigs:(id)sender
{
	prevInVal = 0;
	prevOutVal = 0;
	totalInMegs = 0;
	totalOutMegs = 0;

}

- (void)windowWillClose: (NSNotification*) aNotification;
{
	timer = [[NSTimer scheduledTimerWithTimeInterval:3
					target:self
					selector:@selector(doWork:)
					userInfo:nil
					repeats:YES] retain];
					
					
	timerWriteToDisk = [[NSTimer scheduledTimerWithTimeInterval:3
					target:self
					selector:@selector(doWriteToDisk:)
					userInfo:nil
					repeats:YES] retain];
}

- (void)awakeFromNib
{
	statusItem = [[[NSStatusBar systemStatusBar] 
      statusItemWithLength:NSVariableStatusItemLength]
      retain];
	[statusItem setHighlightMode:YES];
	[statusItem setTitle:[NSString 
         stringWithString:@"0GB"]]; 
	[statusItem setEnabled:YES];
	[statusItem setToolTip:@"AirportTraffic"];
	
	[statusItem setMenu:theMenu];
}

- (void)applicationDidFinishLaunching: (NSNotification*) aNotification;
{
	prevInVal = 0;
	prevOutVal = 0;
	totalInMegs = 0;
	totalOutMegs = 0;
	totalGigsValue = 0;
		
	[self readDatFile];
	
	timer = [[NSTimer scheduledTimerWithTimeInterval:3
					target:self
					selector:@selector(doWork:)
					userInfo:nil
					repeats:YES] retain];
					
					
	timerWriteToDisk = [[NSTimer scheduledTimerWithTimeInterval:3
					target:self
					selector:@selector(doWriteToDisk:)
					userInfo:nil
					repeats:YES] retain];
}

-(void) doWriteToDisk: (NSTimer*) aTimer
{
	FILE *outfile;	
	char outputFilename[] = "airporttraffic.dat";
	
	outfile = fopen(outputFilename, "w");

	if (outfile != NULL) 
	{
		fprintf(outfile, "%f\n%f\n%lu\n%lu\n", totalInMegs, totalOutMegs, prevInVal, prevOutVal);
		fclose(outfile);
	}
}


-(void) doWork: (NSTimer*) aTimer
{
	const char *airportIPValue = [[airportIP stringValue] UTF8String];
	const char *communityPasswordValue = [[communityPassword stringValue] UTF8String];

	struct snmp_session session; 
	struct snmp_session *sess_handle;

	struct snmp_pdu *pdu;                   
	struct snmp_pdu *response;

	struct variable_list *vars;            

	oid in_oid[MAX_OID_LEN];
	size_t in_len = MAX_OID_LEN;
	oid out_oid[MAX_OID_LEN];
	size_t out_len = MAX_OID_LEN;

	int status;                             
	double inRateValue;
	double outRateValue;

	init_snmp("APC Check");
	snmp_sess_init( &session );
	session.version = SNMP_VERSION_1;
	session.community = (u_char*) communityPasswordValue;
	session.community_len = strlen((const char*)session.community);
	session.peername = (char*) airportIPValue;
	sess_handle = snmp_open(&session);

	pdu = snmp_pdu_create(SNMP_MSG_GET);

	read_objid("IF-MIB::ifInOctets.6", in_oid, &in_len);
	snmp_add_null_var(pdu, in_oid, in_len);
	read_objid("IF-MIB::ifOutOctets.6", out_oid, &out_len);
	snmp_add_null_var(pdu, out_oid, out_len);

	status = snmp_synch_response(sess_handle, pdu, &response);
        
	if ( response )
	{
		vars = response->variables;
		if ( prevInVal != 0 )
		{
			if ( prevInVal > *(vars->val.integer) )
			{
				unsigned long int tmpVal = (4294967295 - prevInVal) + *(vars->val.integer);
				totalInMegs += (tmpVal / 1024.0) / 1024.0;
				inRateValue = ( (tmpVal / 3.0) / 1024.0 );
			}
			else	
			{
				totalInMegs += ( (*(vars->val.integer) - prevInVal) / 1024.0) / 1024.0;
				inRateValue = ( ((*(vars->val.integer) - prevInVal) / 3.0) / 1024.0 );
			}
		}
		prevInVal = *(vars->val.integer);

		vars = vars->next_variable;
		if ( prevOutVal != 0 )
		{
			if ( prevOutVal > *(vars->val.integer) )
			{
				unsigned long int tmpVal = (4294967295 - prevOutVal) + *(vars->val.integer);
				totalOutMegs += (tmpVal / 1024.0) / 1024.0;
				outRateValue = ( (tmpVal / 3.0) / 1024.0 );
			}
			else
			{
				totalOutMegs += ( (*(vars->val.integer) - prevOutVal) / 1024.0) / 1024.0; 		
				outRateValue = ( ((*(vars->val.integer) - prevOutVal) / 3.0) / 1024.0 );
			}
		}
		prevOutVal = *(vars->val.integer);
	
		totalGigsValue = (totalInMegs + totalOutMegs) / 1024.0;

		snmp_free_pdu(response);

		snmp_close(sess_handle);

		[outRate setDoubleValue:outRateValue];
		[inRate setDoubleValue:inRateValue];
		[totalGigs setDoubleValue:totalGigsValue];

		// set the status bar text
		if ([showInRate state] && [showOutRate state] && [showTotal state])
			[statusItem setTitle:[NSString stringWithFormat:@"%1.2fKB/s %1.2fKB/s %1.2fGB", inRateValue, outRateValue, totalGigsValue]];
		if ([showInRate state] && ![showOutRate state] && [showTotal state])
			[statusItem setTitle:[NSString stringWithFormat:@"%1.2fKB/s %1.2fGB", inRateValue, totalGigsValue]];
		if ([showInRate state] && ![showOutRate state] && ![showTotal state])
			[statusItem setTitle:[NSString stringWithFormat:@"%1.2fKB/s", inRateValue]];
			
		if (![showInRate state] && [showOutRate state] && [showTotal state])
			[statusItem setTitle:[NSString stringWithFormat:@"%1.2fKB/s %1.2fGB", outRateValue, totalGigsValue]];
		if (![showInRate state] && [showOutRate state] && ![showTotal state])
			[statusItem setTitle:[NSString stringWithFormat:@"%1.2fKB/s", outRateValue]];
		if ([showInRate state] && [showOutRate state] && ![showTotal state])
			[statusItem setTitle:[NSString stringWithFormat:@"%1.2fKB/s %1.2fKB/s", inRateValue, outRateValue]];
			
		if (![showInRate state] && ![showOutRate state] && [showTotal state])
			[statusItem setTitle:[NSString stringWithFormat:@"%1.2fGB", totalGigsValue]];

	}
	else
	{
		NSAlert *alert = [[NSAlert alloc] init];
		[alert addButtonWithTitle:@"OK"];
		[alert setMessageText:@"Couldn't connect to Airport Extreme"];
		[alert setInformativeText:@"Check the IP & Password in preferences"];
		[alert setAlertStyle:NSWarningAlertStyle];
		[alert runModal];
		[alert release];

		if (timer)
		{
			[timer invalidate];
			[timer release];
	
			[timerWriteToDisk invalidate];
			[timerWriteToDisk release];
	
			timer = 0;
			timerWriteToDisk = 0;
		}
	}
}

@end
